package com.sheepshead.controllers;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sheepshead.enums.SuitEnum;
import com.sheepshead.models.Card;
import com.sheepshead.models.Player;
import com.sheepshead.util.CommonUtil;

public class Main {

	public static void main(String[] args) {
		Logger logger = Logger.getLogger(Main.class);
		List<Player> players = new ArrayList<Player>();
		List<Card> blind = new ArrayList<Card>();
		List<Card> cards = CommonUtil.shuffleCards();
		List<Card> currentPile = new ArrayList<Card>();
		Card lastPlayed = new Card();
		SuitEnum calledSuit = SuitEnum.DIAMONDS;
		SuitEnum leadSuit = SuitEnum.DIAMONDS;
		boolean doubler = false;
		int dealer = 5;
		int lastTrick = 0;
		CommonUtil.initializePlayers(players);
		CommonUtil.dealCards(cards, players, blind);
		// Set point value for hand
		for(Player player : players)
		{
			player.setHandPointValue(Player.calculatePointValue(player.getHand()));
		}
		if(logger.isDebugEnabled())
		{
			for(Player player : players)
			{
					logger.debug("Player " + player.getPosition() + "'s Hand: ");
					for(int i=0; i<player.getHand().size(); i++)
					{
						logger.debug(player.getHand().get(i).getCardName());
						if(i<5)
						{
							logger.debug(", ");
						}
						else
						{
							logger.debug("\n");
						}
					}
					logger.debug("Point Value: " + player.getHandPointValue() + "\n");
			}
			logger.debug("Blind has: ");	
			for(int i=0; i<blind.size(); i++)
			{
				logger.debug(blind.get(i).getCardName());
				if(i<1)
				{
					logger.debug(", ");
				}
				else
				{
					logger.debug("\n");
				}
			}
		}
		if(!CommonUtil.chooseBlind(players, blind))
		{
			doubler = true;
		}
		if(doubler)
		{
			for(Player player : players)
			{
				if(player.isPicked() && !player.isAlone())
				{
					 calledSuit = player.getCalledSuit();
					 break;
				}
				else if(player.isPicked() && player.isAlone())
				{
					calledSuit = SuitEnum.DIAMONDS;
					break;
				}
			}
			CommonUtil.setPartner(players);
			for(int rounds=0; rounds<6; rounds++)
			{
				//TODO: Loop through players based on whoever leads, or whoever took last trick
				for(int i=0; i<5; i++)
				{
					if(i==0)
					{
						lastPlayed = players.get(lastTrick).chooseCardToLead(calledSuit);
						if(lastPlayed.getSuit().equals(calledSuit))
						{
							for(Player player : players)
							{
								player.setKnowPartner(true);
							}
						}
						currentPile.add(lastPlayed);
						players.get(lastTrick).getHand().remove(lastPlayed);
					}
					else
					{
						lastPlayed = players.get(lastTrick).chooseCardToPlay(leadSuit, calledSuit, players, currentPile);
						currentPile.add(lastPlayed);
						players.get(lastTrick).getHand().remove(lastPlayed);
					}
					if(lastTrick==5)
					{
						lastTrick = 0;
					}
					else
					{
						lastTrick++;
					}
				}
				lastTrick = CommonUtil.calculateTrickWinner(currentPile);
			}
		}
	}

}
